package com.zhou.jianzhi.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Jackson配置类，解决日期格式问题
 */
@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 禁用将日期转换为时间戳
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        
        // 注册自定义日期反序列化器
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Date.class, new CustomDateDeserializer());
        objectMapper.registerModule(module);
        
        return objectMapper;
    }

    /**
     * 自定义日期反序列化器，支持多种日期格式
     */
    public static class CustomDateDeserializer extends JsonDeserializer<Date> {
        
        private static final SimpleDateFormat[] DATE_FORMATS = new SimpleDateFormat[] {
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"),
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"),
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
            new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"),
            new SimpleDateFormat("yyyy-MM-dd")
        };

        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
            String dateStr = jsonParser.getText();
            
            // 尝试多种日期格式
            for (SimpleDateFormat dateFormat : DATE_FORMATS) {
                try {
                    return dateFormat.parse(dateStr);
                } catch (ParseException e) {
                    // 尝试下一种格式
                }
            }
            
            throw new IOException("无法解析日期: " + dateStr);
        }
    }
} 